package com.qf.mybatis03.utils;

import com.qf.mybatis03.entity.Book;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BookReader {
    private Integer batchNumber = 1000;
    private String filepath;
    private BufferedReader br;//为了能够持续读取同一个文件

    public BookReader() throws FileNotFoundException {
        this.batchNumber = batchNumber;
        this.filepath = filepath;
        //初始化
        this.br = new BufferedReader(new FileReader(filepath));
    }

    public BookReader(String filepath) throws FileNotFoundException {
        this.filepath = filepath;
        this.br = new BufferedReader(new FileReader(filepath));
    }

    public List<Book> readBatch() throws IOException {
        ArrayList<Book> books = new ArrayList<>();
        String line = null;
        while ((line = br.readLine()) != null) {
            //line-->book对象
            Book book = Book.csvToBook(line);
            books.add(book);
            if (books.size() == batchNumber) {
                return books;
            }
        }
        return books;
    }

    //关闭bufferedReader
    public void close() throws IOException {
        this.br.close();
    }
}
